#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Git Hooks 动态配置系统 - 安装工具
负责安装和配置系统
"""

import os
import sys
import argparse
import subprocess
import shutil
from pathlib import Path
from typing import List, Dict, Any

# 添加项目根目录到 Python 路径
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))

from core.hook_manager import HookManager
from core.config_parser import ConfigParser


class Installer:
    """安装器"""
    
    def __init__(self):
        self.project_root = Path(__file__).parent.parent
        self.logger = self._setup_logger()
    
    def _setup_logger(self):
        """设置日志"""
        import logging
        logger = logging.getLogger(__name__)
        logger.setLevel(logging.INFO)
        
        # 控制台处理器
        handler = logging.StreamHandler()
        formatter = logging.Formatter('%(levelname)s: %(message)s')
        handler.setFormatter(formatter)
        logger.addHandler(handler)
        
        return logger
    
    def install(self, git_dir: str = None, force: bool = False) -> bool:
        """安装系统"""
        self.logger.info("开始安装 Git Hooks 动态配置系统...")
        
        try:
            # 检查 Git 仓库
            if not self._check_git_repo(git_dir):
                self.logger.error("当前目录不是 Git 仓库")
                return False
            
            # 检查是否已安装
            if not force and self._is_installed(git_dir):
                self.logger.warning("系统已安装，使用 --force 参数强制重新安装")
                return False
            
            # 创建必要目录
            self._create_directories()
            
            # 复制配置文件
            self._copy_config_files()
            
            # 安装 Git Hooks
            hook_manager = HookManager()
            if not hook_manager.install_hooks(git_dir):
                self.logger.error("安装 Git Hooks 失败")
                return False
            
            # 安装依赖
            self._install_dependencies()
            
            # 验证安装
            if self._verify_installation():
                self.logger.info("安装完成！")
                self._print_usage_info()
                return True
            else:
                self.logger.error("安装验证失败")
                return False
                
        except Exception as e:
            self.logger.error(f"安装失败: {e}")
            return False
    
    def uninstall(self, git_dir: str = None) -> bool:
        """卸载系统"""
        self.logger.info("开始卸载 Git Hooks 动态配置系统...")
        
        try:
            # 检查 Git 仓库
            if not self._check_git_repo(git_dir):
                self.logger.error("当前目录不是 Git 仓库")
                return False
            
            # 移除 Git Hooks
            if not self._remove_git_hooks(git_dir):
                self.logger.error("移除 Git Hooks 失败")
                return False
            
            # 移除配置文件
            self._remove_config_files()
            
            self.logger.info("卸载完成！")
            return True
            
        except Exception as e:
            self.logger.error(f"卸载失败: {e}")
            return False
    
    def status(self, git_dir: str = None) -> Dict[str, Any]:
        """检查系统状态"""
        status = {
            'installed': False,
            'git_repo': False,
            'hooks_installed': False,
            'config_exists': False,
            'dependencies_installed': False
        }
        
        try:
            # 检查 Git 仓库
            status['git_repo'] = self._check_git_repo(git_dir)
            
            # 检查是否已安装
            status['installed'] = self._is_installed(git_dir)
            
            # 检查 Hooks 是否安装
            status['hooks_installed'] = self._check_hooks_installed(git_dir)
            
            # 检查配置文件
            status['config_exists'] = self._check_config_exists()
            
            # 检查依赖
            status['dependencies_installed'] = self._check_dependencies()
            
        except Exception as e:
            self.logger.error(f"检查状态失败: {e}")
        
        return status
    
    def _check_git_repo(self, git_dir: str = None) -> bool:
        """检查是否为 Git 仓库"""
        try:
            if git_dir:
                git_path = Path(git_dir)
            else:
                result = subprocess.run(['git', 'rev-parse', '--git-dir'], 
                                      capture_output=True, text=True)
                if result.returncode != 0:
                    return False
                git_path = Path(result.stdout.strip())
            
            return git_path.exists() and (git_path / 'config').exists()
        except Exception:
            return False
    
    def _is_installed(self, git_dir: str = None) -> bool:
        """检查是否已安装"""
        try:
            # 检查配置文件
            config_file = self.project_root / 'config' / 'hooks.yaml'
            if not config_file.exists():
                return False
            
            # 检查 Git Hooks
            if not self._check_hooks_installed(git_dir):
                return False
            
            return True
        except Exception:
            return False
    
    def _check_hooks_installed(self, git_dir: str = None) -> bool:
        """检查 Git Hooks 是否已安装"""
        try:
            if not git_dir:
                result = subprocess.run(['git', 'rev-parse', '--git-dir'], 
                                      capture_output=True, text=True)
                if result.returncode != 0:
                    return False
                git_dir = result.stdout.strip()
            
            hooks_dir = Path(git_dir) / 'hooks'
            required_hooks = ['pre-commit', 'commit-msg', 'pre-push']
            
            for hook in required_hooks:
                hook_file = hooks_dir / hook
                if not hook_file.exists():
                    return False
                
                # 检查是否包含我们的标识
                try:
                    with open(hook_file, 'r', encoding='utf-8') as f:
                        content = f.read()
                        if 'Git Hooks 动态配置系统' not in content:
                            return False
                except Exception:
                    return False
            
            return True
        except Exception:
            return False
    
    def _check_config_exists(self) -> bool:
        """检查配置文件是否存在"""
        config_file = self.project_root / 'config' / 'hooks.yaml'
        return config_file.exists()
    
    def _check_dependencies(self) -> bool:
        """检查依赖是否安装"""
        try:
            # 检查 Python 包
            import yaml
            return True
        except ImportError:
            return False
    
    def _create_directories(self):
        """创建必要目录"""
        directories = [
            'config',
            'plugins',
            'plugins/lint',
            'plugins/test',
            'plugins/security',
            'plugins/build',
            'logs'
        ]
        
        for directory in directories:
            dir_path = self.project_root / directory
            dir_path.mkdir(parents=True, exist_ok=True)
            self.logger.info(f"创建目录: {directory}")
    
    def _copy_config_files(self):
        """复制配置文件"""
        # 如果配置文件不存在，创建默认配置
        config_file = self.project_root / 'config' / 'hooks.yaml'
        if not config_file.exists():
            self.logger.info("创建默认配置文件...")
            # 这里可以创建默认配置
            pass
    
    def _install_dependencies(self):
        """安装依赖"""
        self.logger.info("检查依赖...")
        
        try:
            import yaml
            self.logger.info("依赖检查通过")
        except ImportError:
            self.logger.warning("缺少 PyYAML 依赖，请手动安装: pip install PyYAML")
    
    def _verify_installation(self) -> bool:
        """验证安装"""
        try:
            # 检查配置文件
            if not self._check_config_exists():
                return False
            
            # 检查依赖
            if not self._check_dependencies():
                return False
            
            return True
        except Exception:
            return False
    
    def _remove_git_hooks(self, git_dir: str = None) -> bool:
        """移除 Git Hooks"""
        try:
            if not git_dir:
                result = subprocess.run(['git', 'rev-parse', '--git-dir'], 
                                      capture_output=True, text=True)
                if result.returncode != 0:
                    return False
                git_dir = result.stdout.strip()
            
            hooks_dir = Path(git_dir) / 'hooks'
            hook_files = ['pre-commit', 'commit-msg', 'pre-push', 'prepare-commit-msg', 'post-commit', 'post-merge']
            
            for hook_file in hook_files:
                hook_path = hooks_dir / hook_file
                if hook_path.exists():
                    try:
                        with open(hook_path, 'r', encoding='utf-8') as f:
                            content = f.read()
                            if 'Git Hooks 动态配置系统' in content:
                                hook_path.unlink()
                                self.logger.info(f"移除 Hook: {hook_file}")
                    except Exception:
                        pass
            
            return True
        except Exception:
            return False
    
    def _remove_config_files(self):
        """移除配置文件"""
        config_dir = self.project_root / 'config'
        if config_dir.exists():
            shutil.rmtree(config_dir)
            self.logger.info("移除配置文件")
    
    def _print_usage_info(self):
        """打印使用信息"""
        print("\n" + "="*50)
        print("Git Hooks 动态配置系统安装完成！")
        print("="*50)
        print("\n使用说明:")
        print("1. 编辑配置文件: config/hooks.yaml")
        print("2. 添加自定义插件到: plugins/")
        print("3. 查看系统状态: python tools/install.py --status")
        print("4. 卸载系统: python tools/install.py --uninstall")
        print("\n配置文件位置: config/hooks.yaml")
        print("插件目录: plugins/")
        print("日志文件: .git/hooks-controller.log")
        print("\n更多信息请查看 README.md")


def main():
    """主函数"""
    parser = argparse.ArgumentParser(description='Git Hooks 动态配置系统安装工具')
    parser.add_argument('--install', action='store_true', help='安装系统')
    parser.add_argument('--uninstall', action='store_true', help='卸载系统')
    parser.add_argument('--status', action='store_true', help='检查系统状态')
    parser.add_argument('--force', action='store_true', help='强制重新安装')
    parser.add_argument('--git-dir', help='指定 Git 目录')
    
    args = parser.parse_args()
    
    installer = Installer()
    
    if args.install:
        success = installer.install(args.git_dir, args.force)
        sys.exit(0 if success else 1)
    elif args.uninstall:
        success = installer.uninstall(args.git_dir)
        sys.exit(0 if success else 1)
    elif args.status:
        status = installer.status(args.git_dir)
        print("\n系统状态:")
        print(f"  已安装: {'是' if status['installed'] else '否'}")
        print(f"  Git 仓库: {'是' if status['git_repo'] else '否'}")
        print(f"  Hooks 已安装: {'是' if status['hooks_installed'] else '否'}")
        print(f"  配置文件存在: {'是' if status['config_exists'] else '否'}")
        print(f"  依赖已安装: {'是' if status['dependencies_installed'] else '否'}")
        sys.exit(0)
    else:
        parser.print_help()


if __name__ == "__main__":
    main()
